<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="食谱名称" prop="recipeName">
            <el-input
              v-model="formData.recipeName"
              placeholder="请输入食谱名称"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="餐饮套餐" prop="comboId">
            <el-select v-model="formData.comboId" placeholder="请输入餐饮套餐" :clearable="true">
              <el-option
                v-for="dict in comboList"
                :key="dict.id"
                :label="dict.comboName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="食谱类型" prop="recipeType">
            <el-select v-model="formData.recipeType" placeholder="请输入食谱类型" :clearable="true">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.RESTAURANT_RECIPE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注"
              :clearable="true"
              rows="3"
              type="textarea"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图片" prop="imgUrl">
            <UploadImg v-model="formData.imgUrl" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddDish">添加菜品</el-button>
      <el-button @click="clickDeleteDish">删除菜品</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="RestaurantRecipeEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #typeId="{ row }">
        {{ dishTypeList.find((obj) => obj.id === row.dish.typeId).name }}
      </template>
      <template #imgUrl="{ row }">
        <span v-if="row.dish.imgUrl == ''"></span>
        <el-image
          v-else
          preview-teleported
          loading="lazy"
          :src="row.imgUrl"
          :preview-src-list="[row.imgUrl]"
          fit="cover"
          class="w-[100px] h-[100px]"
        />
      </template>
      <template #taboo="{ row }">
        {{
          row.dish.taboo
            .map((element) => {
              return getDictObj(DICT_TYPE.RESTAURANT_DISH_TABOO, element).label
            })
            .join(',')
        }}
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <RestaurantDishSelect ref="dishSelectRef" @select-value="handleSelectDish"
/></template>
<script setup name="RestaurantRecipeEdit" lang="ts">
import * as RestaurantDishApi from '@/api/restaurant/dish'
import * as RestaurantRecipeApi from '@/api/restaurant/recipe'
import * as RestaurantRecipeModel from '@/model/restaurant/recipe/RestaurantRecipe'
import * as RestaurantRecipeDetailModel from '@/model/restaurant/recipe/RestaurantRecipeDetail'
import RestaurantDishSelect from '../restaurantDish/RestaurantDishSelect.vue'
import { DICT_TYPE, getDictObj, getIntDictOptions } from '@/utils/dict'
interface RestaurantRecipeDetailEdit extends RestaurantRecipeDetailModel.RestaurantRecipeDetail {
  dish: {
    name: string
    typeId: string
    price: string
    spicy: string
    taste: string
    flavor: string
    imgUrl: string
    taboo: string[]
  }
  operateType: string
}
interface RestaurantRecipeEdit extends RestaurantRecipeModel.RestaurantRecipe {
  details: RestaurantRecipeDetailEdit[]
}
const dialogTitle = ref('')
const dialogVisible = ref(false)
const { t } = useI18n()
const message = useMessage()
const dishSelectRef = ref()
const dishTypeList = ref()
const comboList = ref()
let formType = ''
const formRef = ref()
const formLoading = ref(false)
const formData = ref<RestaurantRecipeEdit>({
  id: undefined,
  recipeName: '',
  comboId: undefined,
  recipeType: 1,
  remark: '',
  imgUrl: '',
  details: []
})
const formRules = reactive({
  recipeName: [{ required: true, message: '请输入食谱名称', trigger: 'blur' }],
  comboId: [{ required: true, message: '请输入餐饮套餐', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '名称',
    prop: 'dish.name'
  },
  {
    label: '餐品类型',
    prop: 'dish.typeId',
    slot: 'typeId'
  },
  {
    label: '价格',
    prop: 'dish.price'
  },
  {
    label: '辣味',
    prop: 'dish.spicy'
  },
  {
    label: '口感',
    prop: 'dish.taste'
  },
  {
    label: '口味',
    prop: 'dish.flavor'
  },
  {
    label: '图片',
    prop: 'dish.imgUrl',
    slot: 'imgUrl'
  },
  {
    label: '禁忌人群',
    prop: 'dish.taboo',
    slot: 'taboo'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dishTypeList.value = await RestaurantDishApi.listQueryDishType()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  comboList.value = await RestaurantRecipeApi.listQueryCombo()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RestaurantRecipeApi.get(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    recipeName: '',
    comboId: undefined,
    recipeType: 1,
    remark: '',
    imgUrl: '',
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RestaurantRecipeEdit
    if (formType === 'create') {
      await RestaurantRecipeApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await RestaurantRecipeApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const handleSelectDish = (selectDishList) => {
  selectDishList.forEach((element) => {
    const existDetails = formData.value.details.filter((detail) => detail.dishId == element.id)
    if (existDetails.length > 0) {
      existDetails.forEach((detail) => {
        if (formType !== 'create') {
          if (detail.id != undefined) detail.operateType = 'update'
          else detail.operateType = 'new'
        }
      })
      return
    }

    const detail = {
      id: undefined,
      recipeId: formType === 'create' ? undefined : formData.value.id,
      dishId: element.id,
      dish: {
        name: element.name,
        typeId: element.typeId,
        price: element.price,
        spicy: element.spicy,
        taste: element.taste,
        flavor: element.flavor,
        imgUrl: element.imgUrl,
        taboo: element.taboo
      },
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}

const clickAddDish = () => {
  dishSelectRef.value.open()
}

const clickDeleteDish = () => {
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}
</script>
